package com.spring.component.rabbitmq.config;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.spring.component.rabbitmq.Properties;

/**
 * @author liushihua
 * @since 2018年04月11日
 */
@Configuration
public class IotbusRabbitConfig extends RabbitConfig {
  @Autowired
  private Properties rabbitProperties;

  @Bean("iotbusConnectionFactory")
  public ConnectionFactory connectionFactory() {
    if (rabbitProperties.validIotbusQueue()) {
      return this.instanceConnectionFactory(rabbitProperties.getIotbusHost(),
          Integer.parseInt(rabbitProperties.getIotbusPort()), rabbitProperties.getIotbusUsername(),
          rabbitProperties.getIotbusPassword(), rabbitProperties.getIotbusVirtualHost());
    } else {
      log.warn("没有配置iotbus mq参数，将不能使用iotbus mq");
      return new CachingConnectionFactory();
    }
  }

  @Bean("iotbusRabbitTemplate")
  public RabbitTemplate rabbitTemplate(
      @Qualifier("iotbusConnectionFactory") ConnectionFactory connectionFactory) {
    return this.instanceRabbitTemplate(connectionFactory);
  }

  @Bean("iotbusRlcFactory")
  public SimpleRabbitListenerContainerFactory containerFactory(
      @Qualifier("iotbusConnectionFactory") ConnectionFactory connectionFactory) {
    return this.instanceFactory(connectionFactory);
  }

  @Bean("iotbusTopicExchange")
  public TopicExchange topicExchange(
      @Qualifier("iotbusConnectionFactory") CachingConnectionFactory connectionFactory) {
    if ("true".equals(this.rabbitProperties.getIotbusExchange())) {
      try {
        this.topicExchangeDeclare(connectionFactory);
        log.info("iotbus exchangeDeclare成功：TOPIC.EXCHANGE");
      } catch (IOException e) {
        log.error("iotbus exchangeDeclare失败：" + e.getMessage());
      } catch (TimeoutException e) {
        log.error("iotbus exchangeDeclare失败，访问超时：" + e.getMessage());
      }
    }
    return new TopicExchange(Properties.TOPIC_EXCHANGE);
  }

}
